package com.example.whatrubbish.service.impl;

import com.example.whatrubbish.mapper.OrderMapper;
import com.example.whatrubbish.model.*;
import com.example.whatrubbish.service.*;
import com.example.whatrubbish.utils.DemoException;
import com.example.whatrubbish.vo.Criteria;
import com.example.whatrubbish.vo.OrderDetailVO;
import com.example.whatrubbish.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserService userService;
    @Autowired
    ReceiverAddressService receiverAddressService;
    @Autowired
    CommodityService commodityService;
    @Autowired
    CommodityDetailService commodityDetailService;
    @Autowired
    IntegrationService integrationService;

    @Override
    public PageBean<OrderDetailVO> selectByCondition(Integer pageIndex, Integer pageSize, String userId, String status, String title) {
        Criteria criteria  = new Criteria();
        criteria.addExtField("pageIndex", pageIndex <= 1 ? 0 : (pageIndex - 1) * pageSize);
        criteria.addExtField("pageSize", pageSize);
        criteria.addExtField("userId", userId);
        criteria.addExtField("status", status);
        criteria.addExtField("title", title);
        Long count = orderMapper.selectByConditionCount(criteria);
        List<Order> orders = orderMapper.selectByCondition(criteria);
        List<OrderDetailVO> orderDetailVOS = orders.stream().map(order -> {
            User user = userService.selectByPrimaryKey(order.getUserId());
            ReceiverAddress receiverAddress = receiverAddressService.selectByPrimaryKey(order.getAddressId());
            Commodity commodity = commodityService.selectByPrimaryKey(order.getCommodityId());
            return new OrderDetailVO(user, receiverAddress, commodity, order);
        }).collect(Collectors.toList());
        PageBean<OrderDetailVO> pageBean = new PageBean<>(pageIndex <= 0 ? 1 : pageIndex, pageSize);
        pageBean.setResultList(orderDetailVOS);
        pageBean.setTotalCount(count);
        return pageBean;
    }

    @Transactional
    @Override
    public int insert(Order record) throws DemoException {
        record.setStatus("0");
        record.setCreateTime(new Date());
        Commodity commodity = commodityService.selectByPrimaryKey(record.getCommodityId());
        Integration integration = integrationService.selectByUserId(record.getUserId());
        if (integration.getScore() < commodity.getPrice()) {
            throw new DemoException("积分不足");
        }
        if (commodity.getAmount() < 1) {
            throw new DemoException("该商品已售完");
        }
        if (commodity.getStatus() != 0) {
            throw new DemoException("该商品已下架");
        }
        // 库存
        commodity.setAmount(commodity.getAmount() - 1);
        commodityService.update(commodity);

        // 销量
        CommodityDetail commodityDetail = commodityDetailService.selectByCommodityId(commodity.getId());
        commodityDetail.setSales(commodityDetail.getSales() + 1);
        commodityDetailService.updateByPrimaryKeySelective(commodityDetail);

        // 扣除积分
        integration.setScore(integration.getScore() - commodity.getPrice());
        integrationService.update(integration);
        return orderMapper.insertSelective(record);
    }

    @Override
    public int update(Order record) {
        return orderMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int delete(Long id) {
        return orderMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    @Override
    public int cancel(Long id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        order.setStatus("3");

        Commodity commodity = commodityService.selectByPrimaryKey(order.getCommodityId());
        // 返还积分
        Integration integration = integrationService.selectByUserId(order.getUserId());
        integration.setScore(integration.getScore() + commodity.getPrice());
        integrationService.update(integration);

        // 库存
        commodity.setAmount(commodity.getAmount() + 1);
        commodityService.update(commodity);

        // 销量
        CommodityDetail commodityDetail = commodityDetailService.selectByCommodityId(commodity.getId());
        commodityDetail.setSales(commodityDetail.getSales() - 1);
        commodityDetailService.updateByPrimaryKeySelective(commodityDetail);
        return orderMapper.updateByPrimaryKeySelective(order);
    }
}
